// 创建用户相关的小仓库
import { defineStore } from 'pinia'
// 引入登录接口
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user/index'
import type {
  loginFormData,
  loginResponseData,
  userInfoReponseData,
} from '@/api/user/type'
import { ElMessage } from 'element-plus'
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from '@/utils/token'
// 引入类型
import type { UserState } from './types/type.ts'
//引入路由(常量路由)
import { constantRouters, asnycRoute, anyRoute } from '@/router/routers.ts'
//引入深拷贝方法
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
//@ts-expect-error
import cloneDeep from 'lodash/cloneDeep'
import router from '@/router'
// 用来过滤用户路由信息
function filterAsyncRoute(asnycRoute: any, routesData: any) {
  return asnycRoute.filter((item: any) => {
    if (routesData.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routesData)
      }
      return true
    }
  })
}
// 退出登录删除已经注册的路由
function resetRouter() {
  const routers = router.getRoutes()
  routers.map((it) => {
    if (!['login', '404', 'layout', 'Screen'].includes(it.name)) {
      router.removeRoute(it.name)
    }
  })
}
export const useuserStore = defineStore('user', {
  // 小仓库存储数据的地方
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //token
      menuRoutes: constantRouters, //仓库存储生成菜单需要数组(路由)
      username: '',
      avatar: '',
      //存储当前用户是否包含某一个按钮
      buttons: [],
    }
  },
  // 异步|逻辑的地方
  actions: {
    // 用户登录
    async userLogin(data: loginFormData) {
      // console.log(data)
      const res: loginResponseData = await reqLogin(data)
      // console.log(res)
      if (res.code == 200) {
        this.token = res.data
        SET_TOKEN(res.data)
        return res.ok
      } else {
        ElMessage({
          message: '密码或账号错误',
          type: 'error',
        })
        return Promise.reject(res)
      }
    },
    // 获取用户信息的方法
    async userinfo() {
      // 获取用户信息存储到仓库当中
      const res: userInfoReponseData = await reqUserInfo()
      const routesData = res.data.routes
      // console.log(res, 123213)
      if (res.code == 200) {
        this.username = res.data.name
        this.avatar = res.data.avatar
        this.buttons = res.data.buttons
        // 对用户拥有的路由权限进行过滤
        const userAsyncRoute = filterAsyncRoute(
          cloneDeep(asnycRoute),
          routesData,
        )
        // console.log(router.getRoutes(), 123123)
        //菜单需要的数据整理完毕
        this.menuRoutes = [...constantRouters, ...userAsyncRoute, anyRoute]
        //目前路由器管理的只有常量路由:用户计算完毕异步路由、任意路由动态追加
        ;[...userAsyncRoute, anyRoute].forEach((route: any) => {
          router.addRoute(route)
        })
        return res.ok
      } else {
        return Promise.reject(new Error(res.message))
      }
    },
    // 用户退出登录
    async userLogout() {
      //退出登录请求
      const result: any = await reqLogout()
      if (result.code == 200) {
        //目前没有mock接口:退出登录接口(通知服务器本地用户唯一标识失效)
        this.token = ''
        this.username = ''
        this.avatar = ''
        resetRouter()
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  // 计算属性
  getters: {},
})
// 对外暴露小仓库的方法
export default useuserStore
